import models.db as db
from flask import request,  jsonify


# 获取项目列表
def item_view():
    message = request.get_json()
    sql = "select * from item where pro_name like @pro_name"
    p = "%" + message["msg"] + "%"
    rows = db.get_db(sql, (p,))
    rows = [dict(row) for row in rows]
    return jsonify(rows)


# 添加项目
def item_add():
    message = request.get_json()
    print(message)
    message_data = []
    sum_data = []
    for i in message.values():
        if isinstance(i, list) is True:
            list_01 = [str(j) for j in i]
            i = ', '.join(list_01)
        message_data.append(i)
    sum_data.append(tuple(message_data))
    sql = "insert into item " \
          "(pro_name, pro_index, pro_system, pro_leader, pro_members, " \
          "pro_starttime, pro_endtime, pro_level, pro_state, pro_description)" \
          " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
    db.query_db(sql, sum_data)
    return jsonify({})


# 打开编辑项目
def item_edit_open():
    message = request.get_json()
    print(message)
    num = message['pro_id']
    sql = "select * from item where pro_id = ?"
    rows = db.get_db(sql, (num,))
    rows = [dict(row) for row in rows]
    print(rows)
    # if rows[0]['pro_members'] != '':
    #     rows[0]['pro_members'] = rows[0]['pro_members'].split(', ')
    return jsonify(rows)


# 编辑项目
def item_edit():
    # message = request.get_json()
    # list_01 = [str(j) for j in message['pro_members']]
    # message['pro_members'] = ', '.join(list_01)
    # sql = "update item set pro_index=" + "'" + message['pro_index'] + "'" + "," + \
    #       "pro_system=" + "'" + message['pro_system'] + "'" + "," + \
    #       "pro_leader=" + "'" + message['pro_leader'] + "'" + "," + \
    #       "pro_members=" + "'" + message['pro_members'] + "'" + "," + \
    #       "pro_starttime=" + "'" + message['pro_starttime'] + "'" + "," + \
    #       "pro_endtime=" + "'" + message['pro_endtime'] + "'" + "," + \
    #       "pro_level=" + "'" + message['pro_level'] + "'" + "," + \
    #       "pro_state=" + "'" + message['pro_state'] + "'" + "," + \
    #       "pro_description=" + "'" + message['pro_description'] + "'" \
    #       + "where pro_name=" + "'" + message['pro_name'] + "'"
    # rows = db.query_db(sql)
    # rows = [dict(row) for row in rows]
    # return jsonify(rows)
    message = request.get_json()
    print(message)
    message_data = []
    sum_data = []
    for i in message.values():
        message_data.append(i)
    sum_data.append(tuple(message_data))
    sql = "update users set pro_index=?, pro_system=? pro_leader=? where name=?"
    db.query_db(sql, sum_data)
    return jsonify({'status': '200', 'msg': '修改成功！'})